package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.exception.CustomException;
import cn.wolfcode.p2p.base.service.ISendVerifyCodeService;
import cn.wolfcode.p2p.base.vo.LoginInfoVO;
import cn.wolfcode.p2p.base.vo.VerifyCodeVO;
import cn.wolfcode.p2p.config.SmsProperties;
import cn.wolfcode.p2p.enums.ErrorCode;
import cn.wolfcode.p2p.util.Assert;
import cn.wolfcode.p2p.util.DateUtil;
import cn.wolfcode.p2p.util.HttpUtil;
import cn.wolfcode.p2p.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

import static cn.wolfcode.p2p.util.Constants.*;

@Service
@Slf4j
@Transactional
public class SendVerifyCodeServiceImpl implements ISendVerifyCodeService {
    @Autowired
    private SmsProperties smsProperties;

    @Override
    public void sendVerifycode(String phone) {
        //判断手机号
        Assert.isPhoneNum(phone, ErrorCode.LOGININFO_USERNAME_FORMAT_ERROR.getErrorMessage());

        //发送频繁,上一次发送时间和当前发送时间间隔不能太短,获取到上一次发送的时间
        VerifyCodeVO verifycodeVo = UserContext.getVerifycodeVo();
        Date currentTime = new Date();
        if (verifycodeVo != null) {
            Date lastSendTime = verifycodeVo.getSendTime();
            Assert.isFalse(DateUtil.getSecondsBetween(lastSendTime, currentTime) < LENGTH_VERIFYCODE_TIME, "操作频繁,请稍后操作");
        }

        //创建验证码
        String code = UUID.randomUUID().toString().substring(0, 4);

        //发送验证码 (模拟)
        log.debug(code);
        send(code, phone);

        //设置值
        VerifyCodeVO verifyCodeVO = new VerifyCodeVO();
        verifyCodeVO.setCode(code);
        verifyCodeVO.setPhoneNum(phone);
        verifyCodeVO.setSendTime(currentTime);

        //保存到session中
        UserContext.setVerifycodeVO(verifyCodeVO);
    }

    private void send(String code, String phone) {
        HashMap<String, String> map = new HashMap<>();
        map.put("Uid", smsProperties.getUid());
        map.put("Key", smsProperties.getKey());
        map.put("smsMob", phone);
        map.put("smsText", MessageFormat.format(smsProperties.getSmsText(), code));

        try {
            String result = "1";//HttpUtil.sendHttpRequest(smsProperties.getUrl(), map);
            Assert.isNotEquals(result, "-3", "验证码发送失败,请联系客服[109]");

        } catch (CustomException e) {
            log.debug("发送失败");
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            log.error("***发送失败");
            e.printStackTrace();
            throw new CustomException("验证码发送失败");
        }
    }

}
